package com.lb.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;

import java.util.Random;

public class SmsUtil {

    // 阿里云短信服务配置
    private static final String ACCESS_KEY_ID = "LTAI5tA8hQ4MLdnBvWCBv7jx"; // 替换为你的 AccessKeyId
    private static final String ACCESS_KEY_SECRET = "tIDJjsomrSK3X6FHuyjZwiR5w4Jvmg"; // 替换为你的 AccessKeySecret
    private static final String ENDPOINT = "dysmsapi.aliyuncs.com"; // 阿里云短信服务的 Endpoint
    private static final String SIGN_NAME = "点单"; // 替换为你的短信签名
    private static final String TEMPLATE_CODE = "SMS_309370273"; // 替换为你的短信模板 CODE

    /**
     * 发送短信验证码
     * @param phoneNumbers 接收短信的手机号码
     * @return 返回生成的验证码，便于后续验证
     * @throws Exception 如果发送失败，抛出异常
     */
    public static String sendSms(String phoneNumbers) throws Exception {
        // 生成四位随机验证码
        String code = generateVerificationCode();

        // 创建配置
        Config config = new Config()
                .setAccessKeyId(ACCESS_KEY_ID)
                .setAccessKeySecret(ACCESS_KEY_SECRET);
        config.endpoint = ENDPOINT;

        // 创建客户端
        Client client = new Client(config);

        // 创建发送短信请求
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumbers)
                .setSignName(SIGN_NAME)
                .setTemplateCode(TEMPLATE_CODE)
                .setTemplateParam("{\"code\":\"" + code + "\"}");

        // 发送短信
        try {
            SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
            System.out.println("短信发送成功，返回码: " + response.getBody().getCode());
            return code; // 返回生成的验证码
        } catch (TeaException error) {
            System.err.println("短信发送失败，错误信息: " + error.getMessage());
            throw error;
        } catch (Exception error) {
            TeaException teaError = new TeaException(error.getMessage(), error);
            System.err.println("短信发送失败，错误信息: " + teaError.getMessage());
            throw teaError;
        }
    }

    /**
     * 生成四位随机验证码
     * @return 返回四位随机验证码
     */
    private static String generateVerificationCode() {
        Random random = new Random();
        int code = random.nextInt(10000); // 生成 0 到 9999 的随机整数
        return String.format("%04d", code); // 确保是四位数字，不足四位时前面补0
    }

    // 测试方法

}